package cn.hbads.support.id.support;


import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Setter
@Component
@NoArgsConstructor
public class SnowIdGenerator {

    // 2025-01-01 00:00:00的时间戳
    private static final long START_TIMESTAMP = 1735660800000L;
    // 位数分配
    private static final int TIMESTAMP_BITS = 31;
    private static final int WORKER_ID_BITS = 5;
    private static final int DATA_CENTER_ID_BITS = 3;
    private static final int SEQUENCE_BITS = 11;

    // 最大值 用来&
    private static final long MAX_TIMESTAMP = (1L << TIMESTAMP_BITS) - 1;
    private static final long MAX_WORKER_ID = (1L << WORKER_ID_BITS) - 1;
    private static final long MAX_DATA_CENTER_ID = (1L << DATA_CENTER_ID_BITS) - 1;
    private static final long MAX_SEQUENCE = (1L << SEQUENCE_BITS) - 1;

    // 位置
    private static final int TIMESTAMP_SHIFT = SEQUENCE_BITS + DATA_CENTER_ID_BITS + WORKER_ID_BITS;
    private static final int WORKER_ID_SHIFT = SEQUENCE_BITS + DATA_CENTER_ID_BITS;
    private static final int DATA_CENTER_ID_SHIFT = SEQUENCE_BITS;

    public SnowIdGenerator(Integer dataCenterId, Integer workerId) {
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
    }

    @Value("${snowflake.datacenter-id:0}")
    private Integer dataCenterId;
    @Value("${snowflake.worker-id:0}")
    private Integer workerId;


    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public synchronized long nextId() {
        long currentTimestamp = System.currentTimeMillis();
        // 时钟回拨检测
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨");
        }

        if (lastTimestamp == currentTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 当前毫秒耗尽
            if (sequence == 0) {
                currentTimestamp = waitNextMills(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = currentTimestamp;
        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    private long waitNextMills(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

}
